package jp.co.baka.pachinko.controller.regist;

import java.util.Date;
import java.util.UUID;

import jp.co.baka.pachinko.costant.CounterNames;
import jp.co.baka.pachinko.meta.UserMstMeta;
import jp.co.baka.pachinko.model.CounterMst;
import jp.co.baka.pachinko.model.UserMst;
import jp.co.baka.pachinko.service.CounterService;
import jp.co.baka.pachinko.service.UserService;
import jp.co.baka.pachinko.util.LogicalErrors;
import jp.co.baka.pachinko.util.MyContrller;

import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.datastore.Datastore;
import org.slim3.datastore.GlobalTransaction;

import com.google.appengine.api.datastore.Key;



/**
 *
 * ユーザ登録(簡易）
 *
 * @author takemura
 *
 */
public class RegistSimpleController extends MyContrller {



    @Override
    public Navigation run() throws Exception {

        if(!validate()){
            return forward("regist_simple.jsp");
        }


        String userName = param("userName");

        //ユーザ名重複チェック
        UserMstMeta u = UserMstMeta.get();
        UserMst record = Datastore.query(u).filter(u.userName.equal(userName)).asSingle();
        if(record!=null){
            LogicalErrors.addErrMessage("既に使われています。");
            return forward("regist_simple.jsp");
        }




        UserMst user = new UserMst();

        String uuid = UUID.randomUUID().toString();

        Key counterKey = CounterService.getCounterKey(CounterNames.USER_MST_USER_ID);

        //トランザクションスタート
        GlobalTransaction gtx = Datastore.beginGlobalTransaction();

        CounterMst counter = gtx.get(CounterMst.class,counterKey);
        counter.increment();

        Date now = new Date();
        user.setUserName(userName);
        user.setUuid(uuid);
        user.setUserId(counter.getCountValue());
        user.setInsertDate(now);
        user.setRegistDate(now);

        gtx.put(user);
        gtx.put(counter);

        gtx.commit();


        UserService.addSessionAndCookie(user,request,response);


        return forward("regist_complete.jsp");
    }


    protected boolean validate() {
        Validators v = new Validators(request);
        v.add("userName", v.required("なまえを入力してください"));
        return v.validate();

    }

}
